package com.xzq.erp.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzq.erp.enums.ResponseCodeEnum;
import com.xzq.erp.utils.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 自定义认证失败处理器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        log.error("认证失败: {}", authException.getMessage());
        
        Response<Object> errorResponse = Response.fail(
            ResponseCodeEnum.UNAUTHORIZED.getErrorCode(),
            ResponseCodeEnum.UNAUTHORIZED.getErrorMessage()
        );
        
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        
        response.getWriter().write(objectMapper.writeValueAsString(errorResponse));
    }
} 